

//
//  DealPhotosView.m
//  Qianbancaifu
//
//  Created by SYLH on 16/1/5.
//  Copyright © 2016年 SYLH. All rights reserved.
//

#import "DealPhotosView.h"
#import "ZoomScrollView.h"
#import "MyActionSheetView.h"
#import "FullScreenImage.h"

@interface DealPhotosView ()<UIScrollViewDelegate,UIActionSheetDelegate,ZoomScrollViewDelegate>
{
    long  _currentPage;
    long  _pageSize;
}

@property (nonatomic,strong) NSMutableArray * imageDataSource;

@property (nonatomic,strong) NSMutableArray * imageViewArray;

@property (nonatomic,strong) NSArray * QRCodeArray;

@property (nonatomic,strong) UIScrollView * scrollView;

@property (nonatomic,strong) ZoomScrollView * currentZoomView;

@property (nonatomic,strong) UIPageControl * pageControl;

@property (nonatomic,strong) UILabel * pageLabel;

@property (nonatomic,strong) UIView * animationAlphaView;


@end

@implementation DealPhotosView


-(instancetype)init
{
    if (self = [super init]) {
        
    }
    return self;
}

-(UIScrollView *)scrollView
{
    if(!_scrollView){
        _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        [_scrollView setContentSize:CGSizeMake(CGRectGetWidth(self.bounds) * 3, CGRectGetHeight(self.bounds))];
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.pagingEnabled = YES;
        _scrollView.bounces = NO;
        _scrollView.delegate = self;
        _scrollView.backgroundColor = [UIColor blackColor];
        [self addSubview:_scrollView];
    }
    return _scrollView;
}

-(UIPageControl *)pageControl
{
    if (!_pageControl) {
        _pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(0, CGRectGetHeight(self.bounds) - 60, CGRectGetWidth(self.bounds), 30)];
        _pageControl.numberOfPages = _pageSize;
        _pageControl.currentPage = _currentPage;
        _pageControl.pageIndicatorTintColor = [UIColor colorWithWhite:0.5 alpha:1.0];
        _pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
        [self addSubview:_pageControl];
    }
    _pageControl.hidden = NO;
    if (_pageSize > 6) {
        _pageControl.hidden = YES;
    }
    if (_pageSize == 1) {
        _pageControl.hidden = YES;
    }
    return _pageControl;
}

-(UILabel *)pageLabel
{
    if (!_pageLabel) {
        _pageLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.bounds) - 60, CGRectGetWidth(self.bounds), 30)];
        _pageLabel.textColor = [UIColor whiteColor];
        _pageLabel.textAlignment = NSTextAlignmentCenter;
        _pageLabel.font = PFM_FONT(14);
        [self addSubview:_pageLabel];
    }
    _pageLabel.hidden = NO;
    if (_pageSize <= 6) {
        _pageLabel.hidden = YES;
    }
    if (_pageSize == 1) {
        _pageLabel.hidden = YES;
    }
    return _pageLabel;
}

#pragma mark - 添加手势
-(void)addGestures
{
    //长按手势
    UILongPressGestureRecognizer * longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(processGesture:)];
    [self.scrollView addGestureRecognizer:longPress];
    //点击手势识别器
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(processGesture:)];
    [self.scrollView addGestureRecognizer:tap];
    //双击手势
    UITapGestureRecognizer * doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTap)];
    doubleTap.numberOfTapsRequired = 2;
    [self addGestureRecognizer:doubleTap];
    [tap requireGestureRecognizerToFail:doubleTap];
}

-(void)addFullImageViews
{
    self.imageViewArray = [NSMutableArray array];
    
    for (int i = 0; i < 3; i ++) {
        ZoomScrollView * zoomView = [[ZoomScrollView alloc]initWithFrame:CGRectMake(i * CGRectGetWidth(self.bounds), 0, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds))];
        zoomView.delegate = self;
        [self.scrollView addSubview:zoomView];
        [self.imageViewArray addObject:zoomView];
        
        if (i == 1) {
            self.currentZoomView = zoomView;
        }
    }
}

-(UIView *)animationAlphaView
{
    if (!_animationAlphaView) {
        _animationAlphaView = [[UIView alloc] initWithFrame:self.frame];
        _animationAlphaView.backgroundColor = [UIColor blackColor];
        [self addSubview:_animationAlphaView];
    }
    return _animationAlphaView;
}

-(void)setFullScreenWithImageArray:(NSArray *)imagesArray showIndex:(NSInteger)index
{
    self.frame = [UIScreen mainScreen].bounds;
    self.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.0];
    
    self.imageDataSource = [NSMutableArray arrayWithArray:imagesArray];
    
    _pageSize = self.imageDataSource.count;
    _currentPage = index;
    
    [self setCycleData];
    
    [self addGestures];
    
    [self addFullImageViews];
    
    [self scrollImageAndSetPageSize:_currentPage];
    
    [self setFullAnimationIsShow:YES];
    
    [[KWindowViewMgr shared] addKWindowViews:self];
    
}

-(void)scrollImageAndSetPageSize:(NSInteger)page
{
    self.pageControl.currentPage = page;
    _currentPage = self.pageControl.currentPage + 1;
    self.pageLabel.text = [NSString stringWithFormat:@"%ld/%ld",_currentPage,_pageSize];
    
    [self setImageToImageView];
    [self.scrollView setContentOffset:CGPointMake(CGRectGetWidth(self.bounds), 0)];
}



-(void)setCycleData
{
    id lastObject = self.imageDataSource.lastObject;
    [self.imageDataSource insertObject:lastObject atIndex:0];
    [self.imageDataSource removeLastObject];

    id fisrtObject;
    for (int i = 0; i < _currentPage ; i++) {
        fisrtObject = self.imageDataSource[0];
        [self.imageDataSource addObject:fisrtObject];
        [self.imageDataSource removeObjectAtIndex:0];
    }
    
    if (_pageSize == 1) {
        self.scrollView.scrollEnabled = NO;
        [self.imageDataSource addObject:self.imageDataSource[0]];
        [self.imageDataSource addObject:self.imageDataSource[0]];
    }else if (_pageSize == 2){
        [self.imageDataSource addObject:self.imageDataSource[0]];
        [self.imageDataSource addObject:self.imageDataSource[1]];
    }
}


//给三个图片视图设置图片
-(void)setImageToImageView
{
    int i = 0;
    for (ZoomScrollView * zoomView in self.imageViewArray) {

        zoomView.imageModel = self.imageDataSource[i];

        zoomView.scrollView.contentSize = zoomView.imgView.frame.size;
        [zoomView.scrollView setZoomScale:1 animated:NO];
        
        i++;
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSInteger  page = 0;
    
    if (scrollView.contentOffset.x >= 2 * CGRectGetWidth(self.bounds)){
        //往右滚动
        id fisrtImage = self.imageDataSource[0];
        [self.imageDataSource removeObjectAtIndex:0];
        [self.imageDataSource addObject:fisrtImage];
        
        
        page = self.pageControl.currentPage == _pageSize - 1 ? 0: self.pageControl.currentPage + 1;
        
    }else if (scrollView.contentOffset.x <= 0){
        // 往左滚动
        id lastImage = self.imageDataSource.lastObject;
        [self.imageDataSource removeLastObject];
        [self.imageDataSource insertObject:lastImage atIndex:0];

        page = self.pageControl.currentPage == 0 ? _pageSize - 1 :self.pageControl.currentPage - 1;
        
    }else{
        return;
    }

    [self scrollImageAndSetPageSize:page];
}

#pragma mark - 手势
- (void) processGesture:(UISwipeGestureRecognizer *)gesture
{
    //点击手势
    if ([gesture isKindOfClass:[UITapGestureRecognizer class]]) {
        
        [self setFullAnimationIsShow:NO];
        
    }else if ([gesture isKindOfClass:[UILongPressGestureRecognizer class]]) {
        // 长按手势
        if (gesture.state == UIGestureRecognizerStateEnded  || gesture.state ==UIGestureRecognizerStateChanged) {
            //sender.state ==UIGestureRecognizerStateChanged这个限制不添加也不影响执行一次的功能，只是若长按住View不放手，一直在上面拖动的话，会一直响应下面else
            return;
        }else {
            //这里长按一次只会进入一次
            UIImage * image = self.currentZoomView.imgView.image;
            [self moreActionWithImage:image];
        }
    }
    
}

#pragma mark - 更多选项
-(void)moreActionWithImage:(UIImage *)image
{
    self.QRCodeArray = [[QRCodeTool recognitionQRCodeWithImage:image] copy];
    NSArray * titleArray;
    NSArray * titleColorArray;
    UIColor * titleColor = [UIColor colorWithHex:0x525151 alpha:1.0];
    
    if (self.QRCodeArray.count > 0) {
        titleArray = @[@"保存到手机",
                       @"识别图中二维码"];
        titleColorArray = @[titleColor,titleColor];
    }else{
        titleArray = @[@"保存到手机"];
        titleColorArray = @[titleColor];
    }
    MyActionSheetView * actionView = [[MyActionSheetView alloc] initWithFrame:self.bounds
                                                               withTitleArray:titleArray
                                                               withColorArray:titleColorArray
                                                                  actionBlock:^(NSInteger index) {

                                                                      if (index == 0){ //保存到手机
                                                                          [self saveImageToPhone:image];
                                                                      }else if (index == 1){ //识别图中二维码
                                                                          [self recognitionQRCode];
                                                                          [self setFullAnimationIsShow:NO];
                                                                      }
                                                                  } cancalBlock:^{

                                                                  }];
    actionView.cancelColor = titleColor;
    [self addSubview:actionView];
}


#pragma mark - 保存图片到相册
-(void)saveImageToPhone:(UIImage *)image
{
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (error) {
        [UITool showHudWithText:[error localizedDescription] withView:self];
    }else{
        [UITool showHudWithText:KNSLocal(@"saveImageSuccess") withView:self];
    }
}

#pragma mark - 识别图中二维码
-(void)recognitionQRCode
{
    NSString * qrUrl = @"";
    for (int i = 0; i < self.QRCodeArray.count; i++) {
        qrUrl = self.QRCodeArray[i];
        if (qrUrl.length != 0) {
            break;
        }
    }
    NSLog(@"图中二维码地址：%@",qrUrl);
    [QRCodeTool analysisQRCodeURLAndDealWithUrl:qrUrl];
}

#pragma mark - 图片缩放
- (void)doubleTap
{
    if (self.currentZoomView.scrollView.zoomScale == 1) {
        [UIView animateWithDuration:0.2 animations:^{
            self.currentZoomView.scrollView.zoomScale = 3.0;
        }];
    }else{
        [UIView animateWithDuration:0.2 animations:^{
            self.currentZoomView.scrollView.zoomScale = 1.0;
        }];
    }
}


-(void)setFullAnimationIsShow:(BOOL)show
{
    FullScreenImage * imageModel = self.imageDataSource[1];
    
    if (imageModel.showImageView) {
        CGRect rect = CGRectMake(0, 0, 0, 0);
        [self setFrameAndZoom:show isDraging:NO dragRect:rect transValue:0];
        
    }else{
        [self setFrameWithAnimationShow:show];
    }
}

-(void)setFrameAndZoom:(BOOL)zoom
             isDraging:(BOOL)draging
              dragRect:(CGRect)dragRect
            transValue:(double)transValue
{
    FullScreenImage * imageModel = self.imageDataSource[1];
    UIView * imageView = imageModel.showImageView;
    CGRect oriFrame = imageModel.showImageView.frame;
    UIView * oriSuperView = imageModel.showImageView.superview;
    
    //zoom YES放大 NO缩小
    UIImage * showImage;
    showImage = ((UIImageView *)imageView).image;
    
    UIWindow * window=[[[UIApplication sharedApplication] delegate] window];
    CGRect windowRect = [imageView convertRect:imageView.bounds toView:window];
    
    CGFloat imageW = showImage.size.width;
    CGFloat imageH = showImage.size.height;
    
    CGFloat newImageW = KScreen_Width;
    CGFloat newImageH = KScreen_Width / imageW * imageH;
    
    CGFloat beforAlpha = 0.0;
    CGFloat afterAlpha = 0.0;
    
    CGRect beforRect;
    CGRect afterRect;
    
    if (zoom) {
        beforAlpha = 0.0;
        afterAlpha = 0.8;
        
        beforRect = windowRect;
        afterRect = CGRectMake(0, CGRectGetMidY(self.bounds) - newImageH / 2, newImageW, newImageH);
        
    }else{
        beforAlpha = 0.8;
        afterAlpha = 0.0;
        
        if(draging){
            beforRect = dragRect;
        }else{
            beforRect = CGRectMake(0, CGRectGetMidY(self.bounds) - newImageH / 2, newImageW, newImageH);
        }
        afterRect = windowRect;
        
    }

//    //图片宽高比例大于屏幕比例 -> 长图
//    if (imageH / imageW > KScreen_Height / KScreen_Width ) {
//        
//    }else{
//        
//    }
    

    imageView.hidden = NO;
    [imageView removeFromSuperview];
    [self addSubview:imageView];
    imageView.frame = beforRect;
    
    if (!draging) {
        self.animationAlphaView.alpha = beforAlpha;
        [self bringSubviewToFront:imageView];
    }
    self.scrollView.alpha = 0.0;
    self.pageControl.alpha = 0.0;
    self.pageLabel.alpha = 0.0;
    
    [UIView animateWithDuration:0.2 delay:0.0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        if (!draging) {
            self.animationAlphaView.alpha = afterAlpha;
        }
        imageView.frame = afterRect;
        
    } completion:^(BOOL finished) {
        if (!draging) {
            [self.animationAlphaView removeFromSuperview];
            self.animationAlphaView = nil;
        }
        
        [imageView removeFromSuperview];
        [oriSuperView addSubview:imageView];
        imageView.frame = oriFrame;
        
        if (!zoom) {
            [self removeFromSuperview];
        }else{
            self.scrollView.alpha = 1.0;
            self.pageControl.alpha = 1.0;
            self.pageLabel.alpha = 1.0;
        }
    }];
}


-(void)setFrameWithAnimationShow:(BOOL)show
{
    if(show){
        self.alpha = 0.0;
        self.transform = CGAffineTransformMakeScale(0.9, 0.9);
        [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationOptionCurveEaseOut animations:^{
            self.alpha = 1.0;
            self.transform = CGAffineTransformMakeScale(1, 1);
        } completion:^(BOOL finished) {
            
        }];
    }else{
        [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationOptionCurveEaseOut animations:^{
            self.alpha = 0.0;
            self.transform = CGAffineTransformMakeScale(1.5, 1.5);
        } completion:^(BOOL finished) {
            [self removeFromSuperview];
        }];
    }
}

#pragma mark - 图片拖拽delegate
-(void)dragShowImageViewWithDragValue:(double)value
{
    double dragValue = value / 200;
    double alphaValue = 1.0 - dragValue;
    if (alphaValue < 0) {
        alphaValue = 0;
    }
    self.scrollView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:alphaValue];
    self.pageLabel.alpha = 0.0;
    self.pageControl.alpha = 0.0;
    //
    FullScreenImage * imageModel = self.imageDataSource[1];
    imageModel.showImageView.hidden = YES;
}
-(void)loosenShowImageView
{
    
    [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.scrollView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:1.0];
        self.pageLabel.alpha = 1.0;
        self.pageControl.alpha = 1.0;
    } completion:^(BOOL finished) {
        FullScreenImage * imageModel = self.imageDataSource[1];
        imageModel.showImageView.hidden = NO;
    }];
}

-(void)fastDragShowImageViewWithRect:(CGRect)rect transValue:(double)transValue
{
    [self setFrameAndZoom:NO isDraging:YES dragRect:rect transValue:transValue];
}




@end
